package com.isoftstone.wms.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.isoftstone.wms.common.QueryPageParam;
import com.isoftstone.wms.common.Result;
import com.isoftstone.wms.entity.Record;
import com.isoftstone.wms.service.impl.RecordService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wms
 * @since 2025-10-03
 */
@RestController
@RequestMapping("/record")
public class RecordController {
    @Resource
    private RecordService recordService;

    @PostMapping("/listpage")
    public Result listpageC(@RequestBody QueryPageParam query) {
        try {
            // 获取前端传过来的查询参数
            HashMap<String, Object> param = query.getParam();
            Integer goodsId = null; // 货品ID

            // 按货品ID精确查询
            if(param.containsKey("goods")) {
                Object goodsObj = param.get("goods");
                if(goodsObj != null && goodsObj instanceof Integer) {
                    goodsId = (Integer) goodsObj;
                } else if (goodsObj != null && goodsObj instanceof String && StringUtils.isNotBlank((String) goodsObj)) {
                    goodsId = Integer.parseInt((String) goodsObj);
                }
            }

            // 1. 创建分页对象
            Page<Record> page = new Page<>();
            page.setCurrent(query.getPageNum()); // 当前页码
            page.setSize(query.getPageSize());  // 每页条数

            // 2. 创建条件构造器
            LambdaQueryWrapper<Record> wrapper = new LambdaQueryWrapper<>();

            // 按货品ID精确查询
            if(goodsId != null){
                wrapper.eq(Record::getGoods, goodsId);
            }

            IPage<Record> result = recordService.page(page, wrapper);
            return Result.success(result.getRecords(), result.getTotal());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("查询失败: " + e.getMessage());
        }
    }
    
    @PostMapping("/save")
    public Result save(@RequestBody Record record) {
        try {
            // 设置创建时间
            record.setCreatetime(LocalDateTime.now());
            
            // 保存记录
            boolean flag = recordService.save(record);
            if(flag) {
                return Result.success("保存成功");
            } else {
                return Result.fail("保存失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("保存失败: " + e.getMessage());
        }
    }

}